package com.wwwarehouse.financialcenter.fragment.moneywarehouse.bankcard;

import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.fastjson.JSON;
import com.wwwarehouse.common.bean.response.CardDeskFunctionResponseBean;
import com.wwwarehouse.common.bean.response.CommonClass;
import com.wwwarehouse.common.constant.Constant;
import com.wwwarehouse.common.custom_widget.address_dialog.DialogSelectAddressUpdate;
import com.wwwarehouse.common.custom_widget.textinput.TextInputLayout;
import com.wwwarehouse.common.custom_widget.time_pick.ChoosePickerDialog;
import com.wwwarehouse.common.tools.ToastUtils;
import com.wwwarehouse.financialcenter.R;
import com.wwwarehouse.financialcenter.bean.bindingcard.CardTypeListBean;
import com.wwwarehouse.financialcenter.bean.bindingcard.MoneyHouseInfomationBean;
import com.wwwarehouse.financialcenter.constant.FinancialConstant;
import com.wwwarehouse.financialcenter.customview.AutoClickButton;
import com.wwwarehouse.financialcenter.eventbus.BankInfoEvent;
import com.wwwarehouse.financialcenter.fragment.base.TheParentFragment;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import de.greenrobot.event.EventBus;

import static com.wwwarehouse.financialcenter.constant.FinancialConstant.PATH_ADDENTERPRISEBANK;

/**
 * Description: 添加企业银行
 * Copyright  : Copyright (c) 2017
 * Author     : yfwang
 * Date       : 2017/11/9 10:03
 */
@Route(path = PATH_ADDENTERPRISEBANK)
public class AddEnterpriseBankFragment extends TheParentFragment implements View.OnClickListener {

    private TextInputLayout mTilAccount;
    private TextInputLayout mTilCardNumber;
    private EditText mEdtAccount;
    private EditText mEdtCardNumber;
    private RelativeLayout mRelBankName;
    private RelativeLayout mRelBankCity;
    private RelativeLayout mRelBankBranch;
    private TextView mBankName;
    private TextView mBankCity;
    private TextView mBankBranch;
    private AutoClickButton mComfirm;
    private CardTypeListBean.DataBean dataBean;
    private String province;
    private String city;
    private long subbankUkid;
    private String businessId;
    private Bundle bundle;
    private List<TextView> texts;
    boolean isNameRight;
    boolean isAccountRight;


    @Override
    protected int getContentId() {
        return R.layout.financial_center_fragment_add_enterprise_bank;
    }

    @Override
    protected void init(View view) {
        EventBus.getDefault().register(this);
        mTilAccount = findView(view, R.id.til_account);
        mTilCardNumber = findView(view, R.id.til_card_number);
        mEdtAccount = findView(view, R.id.edt_account_name);
        mEdtCardNumber = findView(view, R.id.edt_card_number);
        mRelBankName = findView(view, R.id.rel_bank_name);
        mRelBankCity = findView(view, R.id.rel_bank_city);
        mRelBankBranch = findView(view, R.id.rel_bank_branch);
        mBankName = findView(view, R.id.tv_bank_name);
        mBankCity = findView(view, R.id.tv_bank_city);
        mBankBranch = findView(view, R.id.tv_bank_branch);
        mComfirm = findView(view, R.id.confirm_btn);

        texts = new ArrayList<>();
        texts.add(mEdtAccount);
        texts.add(mEdtCardNumber);
        texts.add(mBankName);
        texts.add(mBankCity);
        texts.add(mBankBranch);
        mEdtAccount.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                mEdtAccount.setHint(getString(R.string.financial_center_bank_inputhint));
                mTilAccount.updateHint();
            }
        });
        mEdtCardNumber.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                mEdtCardNumber.setHint(getString(R.string.financial_center_cardnumber_inputhint));
                mTilCardNumber.updateHint();
            }
        });
        mEdtAccount.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                mEdtAccount.setHint(getString(R.string.financial_center_bank_inputhint));
                mTilAccount.updateHint();
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (mEdtAccount.getText().toString().length() > 40) {
                    mTilAccount.setStateWrong(getString(R.string.financial_center_cardnumber_name_tips));
                    isNameRight = false;
                } else {
                    mTilAccount.setStateNormal();
                    mEdtAccount.setHint(getString(R.string.financial_center_bank_inputhint));
                    mTilAccount.updateHint();
                    isNameRight = true;
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        mEdtCardNumber.addTextChangedListener(new TextWatcher() {
            private int oldLength = 0;
            private boolean isChange = true;
            private int curLength = 0;
            private int emptyNumB = 0;
            private int emptyNumA = 0;

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                mEdtCardNumber.setHint(getString(R.string.financial_center_cardnumber_inputhint));
                mTilCardNumber.updateHint();
                oldLength = s.length();
                emptyNumB = 0;
                for (int i = 0; i < s.toString().length(); i++) {
                    if (s.charAt(i) == ' ') emptyNumB++;
                }

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (mEdtCardNumber.getText().toString().trim().length() < 14 || mEdtCardNumber.getText().toString().trim().length() > 24) {
                    mTilCardNumber.setStateWrong(getString(R.string.financial_center_cardnuber_account_tips));
                    isAccountRight = false;
                } else {
                    mTilCardNumber.setStateNormal();
                    mEdtCardNumber.setHint(getString(R.string.financial_center_cardnumber_inputhint));
                    mTilCardNumber.updateHint();
                    isAccountRight = true;
                }

                curLength = s.length();
                isChange = !(curLength == oldLength || curLength <= 3);


            }

            @Override
            public void afterTextChanged(Editable s) {
                if (isChange) {
                    int selectIndex = mEdtCardNumber.getSelectionEnd();//获取光标位置
                    String content = s.toString().replaceAll(" ", "");
                    StringBuffer sb = new StringBuffer(content);
                    //遍历加空格
                    int index = 1;
                    emptyNumA = 0;
                    for (int i = 0; i < content.length(); i++) {
                        if ((i + 1) % 4 == 0) {
                            sb.insert(i + index, " ");
                            index++;
                            emptyNumA++;
                        }
                    }
                    String result = sb.toString();
                    if (result.endsWith(" ")) {
                        result = result.substring(0, result.length() - 1);
                    }
                    mEdtCardNumber.setText(result);
                    if (emptyNumA > emptyNumB)
                        selectIndex = selectIndex + (emptyNumA - emptyNumB);
                    //处理光标位置
                    if (selectIndex > result.length() || selectIndex + 1 == result.length()) {
                        selectIndex = result.length();
                    } else if (selectIndex < 0) {
                        selectIndex = 0;
                    }
                    mEdtCardNumber.setSelection(selectIndex);
                    isChange = false;
                }

            }
        });

        for (int i = 0; i < texts.size(); i++) {
            texts.get(i).addTextChangedListener(new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                }

                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {
                    changeStatus();
                }

                @Override
                public void afterTextChanged(Editable s) {

                }
            });
        }


        mEdtAccount.setHint(R.string.financial_center_bank_hint);
        mTilAccount.updateHint();
        mEdtCardNumber.setHint(R.string.financial_center_cardnumber_hint);
        mTilCardNumber.updateHint();


        mRelBankName.setOnClickListener(this);
        mRelBankCity.setOnClickListener(this);
        mRelBankBranch.setOnClickListener(this);
        mComfirm.setOnClickListener(this);
        bundle = getArguments();
        if (bundle != null) {
            CardDeskFunctionResponseBean.TaskBean mBean = (CardDeskFunctionResponseBean.TaskBean) bundle.getSerializable(Constant.KEY_CARD_DESK_FUNCTION_DETAILS);
            MoneyHouseInfomationBean.DataBean moneyHomeData = (MoneyHouseInfomationBean.DataBean) bundle.getSerializable("moneyHomeData");
            if (null != mBean) {
                //功能卡
                businessId = mBean.getBusinessId();
            } else if (null != moneyHomeData) {
                //信息卡
                businessId = moneyHomeData.getBusinessId() + "";
            }
        }


    }


    private void changeStatus() {
        for (int i = 0; i < texts.size(); i++) {
            String ss = texts.get(i).getText().toString().trim();
            if (TextUtils.isEmpty(ss)
                    || getString(R.string.financial_center_choose_bank).equals(ss)
                    || getString(R.string.financial_center_choose_city).equals(ss)
                    || getString(R.string.financial_center_choose_branch).equals(ss)||!isAccountRight||!isNameRight) {
                mComfirm.setEnabled(false);
                return;
            }
        }
        mComfirm.setEnabled(true);
    }

    @Override
    public void setTitle() {
        if (peekFragment() instanceof AddEnterpriseBankFragment) {
            mActivity.setTitle(R.string.financial_center_add_enterprise_bank);
        }
    }

    @Override
    public void onSuccess(CommonClass commonClass, int what) {
        if (what == 0) {
            if (TextUtils.equals("0", commonClass.getCode())) {
                final List<CardTypeListBean.DataBean> dataBeen = JSON.parseArray(commonClass.getData().toString(), CardTypeListBean.DataBean.class);
                if (dataBeen != null) {
                    ArrayList<String> strings = new ArrayList<>();
                    for (int i = 0; i < dataBeen.size(); i++) {
                        strings.add(dataBeen.get(i).getBankName());
                    }
                    new ChoosePickerDialog.Builder(mActivity).setTitle(getString(R.string.financial_center_choosebank_title)).setData(strings).setOnDataSelectedListener(new ChoosePickerDialog.OnSelectedListener() {
                        @Override
                        public void onSelected(String itemValue, int position) {
                            mBankName.setText(itemValue);
                            dataBean = dataBeen.get(position);
                            mBankBranch.setText(getString(R.string.financial_center_choose_branch));
                            subbankUkid = -1;
                        }

                        @Override
                        public void onCancel() {

                        }
                    }).create().show();
                }


            } else {
                toast(commonClass.getMsg());
            }
        } else if (what == 1) {
            if (TextUtils.equals("0", commonClass.getCode())) {
                popFragment();
                AddSuccessFragment addSuccessFragment = new AddSuccessFragment();
                addSuccessFragment.setArguments(bundle);
                pushFragment(addSuccessFragment);
            } else {
                ToastUtils.showToastAtTop(commonClass.getMsg());
            }
        }
    }

    public void onEventMainThread(Object event) {
        if (event instanceof BankInfoEvent) {
            popFragment();
            mBankBranch.setText(((BankInfoEvent) event).getListBean().getSubbankName());
            subbankUkid = ((BankInfoEvent) event).getListBean().getSubbankUkid();
        }
    }

    @Override
    public void onReLoad(int code) {

    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.rel_bank_name) {
            httpPost(FinancialConstant.GETSBANKTYPE, new HashMap(), 0, true, "");
        } else if (id == R.id.rel_bank_city) {
            DialogSelectAddressUpdate dialogSelectAddressUpdate = new DialogSelectAddressUpdate(mActivity, true, false);
            dialogSelectAddressUpdate.setListener(new DialogSelectAddressUpdate.AddressListener() {
                @Override
                public void setAddress(String province, String city, String district, String street) {
                    AddEnterpriseBankFragment.this.province = province;
                    AddEnterpriseBankFragment.this.city = city;
                    mBankCity.setText(province + city);
                    mBankBranch.setText(getString(R.string.financial_center_choose_branch));
                    subbankUkid = -1;
                }
            });
            dialogSelectAddressUpdate.show();

        } else if (id == R.id.rel_bank_branch) {
            if (dataBean == null || TextUtils.isEmpty(province) || TextUtils.isEmpty(city)) {
                toast(getString(R.string.financial_center_bindingtips));
            } else {
                Bundle bundle = new Bundle();
                bundle.putString("bankUkid", dataBean.getBankUkid() + "");
                bundle.putString("province", province);
                bundle.putString("city", city);
                AddBankBranchFragment addBankBranchFragment = new AddBankBranchFragment();
                addBankBranchFragment.setArguments(bundle);
                pushFragment(addBankBranchFragment);
            }
        } else if (id == R.id.confirm_btn) {

            Map<String, Object> map = new HashMap<>();
            map.put("accountName", mEdtAccount.getText().toString());
            map.put("accountType", "0");
            map.put("bankUkid", dataBean.getBankUkid());
            map.put("businessId", businessId);
            map.put("cardNo", mEdtCardNumber.getText().toString().replaceAll(" ", ""));
            map.put("cityName", city);
            map.put("provinceName", province);
            map.put("subbankUkid", subbankUkid);
            httpPost(FinancialConstant.BINDBANKINFO, map, 1, true, "");

        }


    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);

    }
}


